package me.lc.rank;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import me.lc.FunPeaceActivity;
import android.os.AsyncTask;

public class GetTop10RankAsyncTask extends
		AsyncTask<Integer, Integer, List<RankInfo>> {
	@Override
	protected List<RankInfo> doInBackground(Integer... types) {
		if (types != null && types.length > 0) {
			Integer type = types[0];
			try {
				List<RankInfo> ranks = new ArrayList<RankInfo>();
				String url = String
						.format("%s%s?type=%d", SAEHelper.SAE_SERVER_URL,
								SAEHelper.GET_TOP10_URL, type);
				URL feedUrl = new URL(url);
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(feedUrl.openConnection()
								.getInputStream()));
				String str = "";
				int i = 1;
				while ((str = reader.readLine()) != null) {
					String[] cols = str.split(",");
					if (cols != null && cols.length == 3) {
						RankInfo info = new RankInfo();
						try {
							String name = cols[0];
							String id = cols[1];
							int score = Integer.parseInt(cols[2]);
							info.setNo(i);
							info.setName(name);
							info.setScore(score);
							info.setSelf(id.equals(FunPeaceActivity.Instance.rankID));
							ranks.add(info);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
					i++;
				}
				return ranks;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	@Override
	protected void onPostExecute(List<RankInfo> ranks) {
		if (ranks != null) {
			try {
				// 更新本地数据库，刷新排行界面
				// RankHelper.updateTop10Rank(ranks);
				// MenuScene.getInstance().getRankLayer().updateTopRank(RankHelper.getTop10Rank());

				RankActivity.top10Info = ranks;
				RankActivity.loadCompleteHadler.sendEmptyMessage(2);

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
